<template>
  <div class="container">
    <h1>Database Operations</h1>
    <div class="form-group">
      <label for="fetchId">Fetch by ID:</label>
      <input type="number" v-model="fetchId" id="fetchId" />
      <button @click="fetchSingleData">Fetch</button>
    </div>
    <table>
      <thead>
        <tr>
          <th @click="sortData('id')">ID</th>
          <th @click="sortData('item_name')">Item Name</th>
          <th @click="sortData('value')">Value</th>
          <th>Actions</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="record in displayedRecords" :key="record.id">
          <td>{{ record.id }}</td>
          <td>{{ record.item_name }}</td>
          <td>{{ record.value }}</td>
          <td>
            <button @click="deleteData(record.id)">Delete</button>
            <router-link :to="{ name: 'update', params: { id: record.id } }">Update</router-link>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script lang="ts">
import { ref, computed, onMounted } from 'vue'

interface Record {
  id: number
  item_name: string
  value: string
}

export default {
  name: 'Home',
  setup() {
    const records = ref<Record[]>([])
    const sortKey = ref<keyof Record>('id')
    const sortOrder = ref<number>(1) // 1 for ascending, -1 for descending
    const fetchId = ref<number | null>(null)

    function fetchData() {
      fetch('/api/data')
        .then((response) => response.json())
        .then((data) => {
          records.value = data
        })
        .catch((error) => {
          console.error('Error:', error)
        })
    }

    function fetchSingleData() {
      if (fetchId.value !== null) {
        fetch(`/api/data/${fetchId.value}`)
          .then((response) => response.json())
          .then((data) => {
            records.value = [data]
          })
          .catch((error) => {
            console.error('Error:', error)
          })
      } else {
        fetchData()
      }
    }

    function deleteData(id: number) {
      fetch(`/api/delete/${id}`, {
        method: 'DELETE'
      })
        .then((response) => response.json())
        .then((data) => {
          alert(data.message)
          fetchData() // Refresh the data
        })
        .catch((error) => {
          console.error('Error:', error)
        })
    }

    function sortData(key: keyof Record) {
      if (sortKey.value === key) {
        sortOrder.value = -sortOrder.value
      } else {
        sortKey.value = key
        sortOrder.value = 1
      }
    }

    const sortedRecords = computed(() => {
      return [...records.value].sort((a, b) => {
        const result = a[sortKey.value] > b[sortKey.value] ? 1 : -1
        return result * sortOrder.value
      })
    })

    const displayedRecords = computed(() => {
      if (fetchId.value !== null) {
        return sortedRecords.value.filter((record) => record.id === fetchId.value)
      }
      return sortedRecords.value
    })

    onMounted(fetchData)

    return {
      fetchId,
      records,
      displayedRecords,
      deleteData,
      sortData,
      fetchSingleData
    }
  }
}
</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  max-width: 800px;
  width: 100%;
  padding: 20px;
  background: #fff;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  border-radius: 10px;
  margin: 50px auto;
}

h1 {
  margin-bottom: 20px;
}

table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px;
}

th,
td {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: left;
}

th {
  background-color: #f2f2f2;
  cursor: pointer;
}

tr:hover {
  background-color: #f1f1f1;
}

button {
  padding: 10px 15px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

button:hover {
  background-color: #0056b3;
}

.form-group {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.form-group input {
  margin-left: 10px;
  padding: 5px;
  border: 1px solid #ddd;
  border-radius: 5px;
}
</style>
